package com.gomore.opple.module.takeandselectphoto;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.gomore.opple.OppleApplication;
import com.gomore.opple.R;
import com.gomore.opple.model.EventPhoto;
import com.gomore.opple.module.BaseActivity;
import com.gomore.opple.module.IntentStart;
import com.gomore.opple.utils.PhotoUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Created by asus on 2017/5/27.
 */
public class TakeAndSelectPhotoActivity extends BaseActivity {
    @Bind(R.id.txt_take_photo)
    TextView txt_take_photo;
    @Bind(R.id.txt_photo_album)
    TextView txt_photo_album;
    @Bind(R.id.cancel)
    TextView cancel;
    private static final int CAMERA_CODE = 1;
    private static final int GALLERY_CODE = 2;
    private static final int CROP_CODE = 3;
    private static final String DATA_ROOT = "/data/data/";
    private static final String PATH = "temp";
    private static final String OPPLE_ICON = "opple_icon.jpg";
    //定义全局Uri
    private Uri imageUri;
    private String fragmentType;
    private int position;

    @Override
    protected void initalizeViewData() {
        super.initalizeViewData();
        if (getIntent() != null && getIntent().getStringExtra(IntentStart.FRAGMENT_TYPE) != null) {
            fragmentType = getIntent().getStringExtra(IntentStart.FRAGMENT_TYPE);
            position = getIntent().getIntExtra(IntentStart.POSITION, 0);
        }
    }

    @Override
    protected void initalizeViews() {
        imageUri = getImageUri(PATH);
    }

    @Override
    protected void initializeDependencyInjector() {

    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_take_and_select;
    }

    @OnClick({R.id.txt_take_photo, R.id.txt_photo_album, R.id.cancel})
    public void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.txt_take_photo:
                chooseFromCamera();
                break;
            case R.id.txt_photo_album:
                chooseFromGallery();
                break;
            case R.id.cancel:
                finish();
                break;
        }
    }

    private Uri getImageUri(String path) {
        //新建文件夹用于存放裁剪后的图片
        File tmpDir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            tmpDir = new File(Environment.getExternalStorageDirectory() + "/" + path);
        } else {
            tmpDir = new File(DATA_ROOT + OppleApplication.getInstance().getPackageName() + "/" + path);
        }
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }
        //新建文件存储图片
        String image_url = tmpDir.getAbsolutePath() + "/" + OPPLE_ICON;
        File file = new File(image_url);
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Uri.fromFile(file);
    }

    /**
     * 拍照选择图片
     */
    private void chooseFromCamera() {
        //构建隐式Intent
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //定义输出路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        //调用系统相机
        startActivityForResult(intent, CAMERA_CODE);
    }

    /**
     * 从相册选择图片
     */
    private void chooseFromGallery() {
        //构建一个内容选择的Intent
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        //设置选择类型为图片类型
        intent.setType("image/*");
        //打开图片选择
        startActivityForResult(intent, GALLERY_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CAMERA_CODE:
                //通过Uri获得拍的照片(图片质量高)
                if (imageUri != null) {
                    //启动图像裁剪
                    // startImageZoom(imageUri);
                    postImage();
                }

                // 通过Bundle来获取拍的照片(图片质量不高，缩略图)
//                if (data == null) {
//                    return;
//                }
//                Bundle extras = data.getExtras();
//                if (extras != null) {
//                    Bitmap bm = extras.getParcelable("data");
//                    //将Bitmap转化为uri
//                    Uri uri = saveBitmap(bm, PATH);
//                   startImageZoom(uri);
//                }
                break;
            case GALLERY_CODE:
                if (data == null) {
                    return;
                }
                //获取到用户所选图片的Uri
                Uri uri = data.getData();
                //注意此时返回的Uri为content类型的Uri,不能进行复制等操作,需要转换为文件Uri
                convertUri(uri);
                //启动图像裁剪
                //startImageZoom(imageUri);
                postImage();
                break;
            case CROP_CODE:
                //截图是大图，用Uri返回,data用于判断是否裁剪取消
//                if (imageUri != null && data != null) {
//                    EventPhoto bitmapEvent = new EventPhoto();
//                    bitmapEvent.setFragmentType(fragmentType);
//                    bitmapEvent.setUrl(imageUri.getPath());
//                    bitmapEvent.setPosition(position);
//                    EventBus.getDefault().post(bitmapEvent);
//                    finish();
//                }

                //截图是小图，用Bitmap返回
//                if (data == null) {
//                    return;
//                }
//                    Bundle extras1 = data.getExtras();
//                    if (extras1 != null) {
//                        Bitmap bm1 = extras1.getParcelable("data");
//                        if (bm1 != null) {
//                            BitmapEvent bitmapEvent = new BitmapEvent();
//                            bitmapEvent.setUrl(image_url);
//                            bitmapEvent.setBitmap(bm1);
//                            EventBus.getDefault().post(bitmapEvent);
//                            finish();
//                        }
//                    }
//                }
                break;
            default:
                break;
        }
    }

    /**
     * 传输图片
     */
    private void postImage() {
        //发送图片
        EventPhoto bitmapEvent = new EventPhoto();
        bitmapEvent.setFragmentType(fragmentType);
        bitmapEvent.setUrl(imageUri.getPath());
        bitmapEvent.setPosition(position);
        EventBus.getDefault().post(bitmapEvent);
        finish();
    }

    /**
     * 将content类型的Uri转化为文件类型的Uri
     *
     * @param uri
     * @return
     */
    private void convertUri(Uri uri) {
        InputStream is;
        try {
            //通过Uri获取字节输入InputStream
            is = getContentResolver().openInputStream(uri);
            //将字节流InputStream转化Bitmap
            Bitmap bm = BitmapFactory.decodeStream(is);
            //关闭流
            is.close();
            //将Bitmap写到内存卡上
            writeBitmapToSdcard(bm);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将Bitmap写入SD卡中的一个文件中，路径为imageUri
     *
     * @param bm
     * @return
     */
    private void writeBitmapToSdcard(Bitmap bm) {
        try {
            String url = imageUri.getPath();
            File file = new File(url);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            //打开文件输出流
            FileOutputStream fos = new FileOutputStream(file);
            //将bitmap压缩后写入输出流(参数依次为图片格式、图片质量和输出流)
            bm.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            //刷新输出流
            fos.flush();
            //关闭输出流
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过Uri传递图像信息以供裁剪
     *
     * @param uri
     */
    private void startImageZoom(Uri uri) {
        // 构建隐式Intent来启动裁剪程序
        Intent intent = new Intent("com.android.camera.action.CROP");
        // 设置数据uri和类型为图片类型
        intent.setDataAndType(uri, "image/*");
        // 显示View为可裁剪的
        intent.putExtra("crop", true);
        // 裁剪的宽高的比例为1:1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 截小图，将数据保留在Bitmap中返回,return-data设置了true的话直接返回bitmap，可能会很占内存
//        intent.putExtra("outputX", 200);
//        intent.putExtra("outputY", 100);
//        intent.putExtra("return-data", true);
        // 截大图
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, CROP_CODE);
    }
}
